# $Id$

class ProjectReport < ActiveRecord::Base
  unloadable
  
  belongs_to :project
  belongs_to :form, :class_name => "ProjectReportForm", :foreign_key => "project_report_form_id"

  include ApplicationHelper

  def self.sanitize_sql_conditions(conditions)
    return sanitize_sql(conditions)
  end

  def teams
    return [] unless self.form
    return [] unless self.form.issue_groups
    self.form.teams
  end

  def issue_groups
    return [] unless self.form
    return [] unless self.form.issue_groups
    self.form.issue_groups
  end

  def estimated_hours(team)
    return 0.0 unless team
    return 0.0 unless team.is_a?(ProjectReportTeam)
    
    return 7.75 * calendar_work_days(self.start_date, self.due_date) * team.members.length
  end

  def spent_hours(team)
    return 0.0 unless team
    return 0.0 unless team.is_a?(ProjectReportTeam)
    return 0.0 if team.members.length == 0

    user_ids = []
    team.members.each {|member| user_ids << member.id}
    return TimeEntry.sum(:hours, :conditions => ["spent_on >= ? and spent_on <= ? and project_id = ? and user_id in (#{user_ids.join(',')})", self.start_date, self.due_date, self.project.id])
  end

  def issues(issue_group)
    return [] unless issue_group
    return [] unless issue_group.is_a?(ProjectReportIssueGroup)

    conds = []
    conds << ProjectReport.sanitize_sql_conditions(["#{Issue.table_name}.start_date >= ?", self.start_date]) if self.start_date
    conds << ProjectReport.sanitize_sql_conditions(["#{Issue.table_name}.due_date <= ?", self.due_date]) if self.due_date
    return issue_group.issues(:conditions => conds.join(" and "))
  end

end
